package servlet;

import bean.Mail;
import dao.MailDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;

/**
 * Created by liu on 2017/9/8.
 */
@WebServlet(name="mailSearchServlet",urlPatterns = "/mailSearchServlet")
public class mailSearchServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String searchKey=req.getParameter("searchKey");
        String title=req.getParameter("title");
        String search_type=req.getParameter("search_type");
        String pageNum=req.getParameter("pageNum");
        if(pageNum==null){
            pageNum="1";
        }
        if(title==null){
            title="";
        }
        if(search_type==null){
            search_type="";
        }
        MailDao dao= null;

            dao = new MailDao();

        req.setAttribute("searchKey",searchKey);
        req.setAttribute("title",title);
        req.setAttribute("search_type",search_type);
        if(searchKey!=null&&searchKey.length()!=0){
            req.setAttribute("totalPages",Integer.valueOf(1));
            ArrayList<Mail> mails=new ArrayList<Mail>();
            Mail m=dao.getMailByKey(searchKey);
            if(m!=null) mails.add(m);
            req.setAttribute("mailList",mails);
        }else {

            req.setAttribute("totalPages",dao.getMailListCount(title,search_type));
            req.setAttribute("mailList",dao.getMailList(title,search_type,Integer.parseInt(pageNum)));
        }
        req.getRequestDispatcher("/mailbox/mailSearch.jsp").forward(req,resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
